package com.example.controller;


import com.example.entity.User;
import com.example.service.SendSms;
import com.example.service.UserService;
import com.example.util.*;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Nostalgia
 * @Date: 2020/6/16 09:53
 * @Description:
 */
@Controller
@RequestMapping("/users")
@CrossOrigin//跨域支持
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SendSms sendSms;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @RequestMapping("/send/{phone}")
    @ResponseBody
    public String send(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return "已存在!";
        }
        code = UUID.randomUUID().toString().substring(0,6);
        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = sendSms.send(phone,"SMS_194920101",param);
        if(isSend){
           /* TimeUnit.DAYS          //天
            TimeUnit.HOURS         //小时
            TimeUnit.MINUTES       //分钟
            TimeUnit.SECONDS       //秒
            TimeUnit.MILLISECONDS  //毫秒*/
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return "发送成功!";
        }else{
            return "发送失败!";
        }
    }
    @RequestMapping("/insert")
    public String insert(){
        return "register";
    }
    @RequestMapping("/register")
    @ResponseBody
    public int register(User user){
        Random random = new Random();
        int num = 0;
        StringBuilder salt = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            num = random.nextInt(10);
            salt.append(num);
        }
        String newpassword = SaltMd5.md5(user.getPassword()+salt);
        user.setPassword(newpassword);
        user.setSalt(salt.toString());
        return userService.register(user);
    }

    @RequestMapping("/yz/{phone}")
    @ResponseBody
    public int yzPhone(@PathVariable("phone") String phone){
        return userService.getPhone(phone);
    }

    @RequestMapping("/dl")
    public String dl(){
        return "login";
    }


    /**
     * 手机验证码登录
     */
    @RequestMapping("/yzmlogin")
    @ResponseBody
    public String yzmlogin(String phone,String code){
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(redisCode ==null){
            return "验证码不存在或者过期";
        }else if(redisCode.equals(code)){
            return "验证通过";
        }else{
            return "验证码错误";
        }
    }
    /**
     * 账密登陆
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public int login(String username,String password){
        String salt = userService.getUserByUsername(username).getSalt();
        String newpassword = SaltMd5.md5(password+salt);
        String pwd = userService.getUserByUsername(username).getPassword();//数据库密码字段
        if(newpassword.equals(pwd)){
            return 1;
        }else{
            return -1;
        }
    }


    @Resource
    private DefaultKaptcha captchaProducer;

    @RequestMapping(value = {"/"})
    public String index() {
        return "/index";
    }

    /**
     * 登录验证码SessionKey
     */
    public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
    /**
     * 登录验证码图片
     */
    @RequestMapping(value = {"/loginValidateCode"})
    public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        CommonUtil.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE);
    }

    /**
     * 检查验证码是否正确
     */
    @RequestMapping("/checkLoginValidateCode")
    @ResponseBody
    public HashMap checkLoginValidateCode(HttpServletRequest request, @RequestParam("validateCode")String validateCode) {
        String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
        HashMap<String,Object> map = new HashMap<String,Object>();
        if(loginValidateCode == null){
            map.put("status",null);//验证码过期
        }else if(loginValidateCode.equals(validateCode)){
            map.put("status",true);//验证码正确
        }else if(!loginValidateCode.equals(validateCode)){
            map.put("status",false);//验证码不正确
        }
        map.put("code",200);
        return map;
    }
}
